package lj.courseinterect.dao;

import lj.courseinterect.dao.i.CourseInfoDao;
import lj.courseinterect.dao.i.StudentDao;
import lj.courseinterect.entity.CourseInfo;
import lj.courseinterect.entity.Student;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Root;
import java.util.List;

public class JpaCourseInfoDao extends JpaDao<CourseInfo, Long> implements CourseInfoDao{

    public JpaCourseInfoDao() {
        super(CourseInfo.class);
    }

    @Override
    public List<CourseInfo> queryByTeaId(Long teaId) {
        final CriteriaBuilder builder = this.getEntityManager().getCriteriaBuilder();
        final CriteriaQuery<CourseInfo> criteriaQuery = builder.createQuery(this.entityClass);

        Root<CourseInfo> root = criteriaQuery.from(this.entityClass);
        Path<String> namePath = root.get("teaId");
        criteriaQuery.where(builder.equal(namePath, teaId));

        TypedQuery<CourseInfo> typedQuery = this.getEntityManager().createQuery(criteriaQuery);
        List<CourseInfo> courseInfos = typedQuery.getResultList();

        return courseInfos;
    }

    @Override
    public CourseInfo findByCouName(String couName) {
        final CriteriaBuilder builder = this.getEntityManager().getCriteriaBuilder();
        final CriteriaQuery<CourseInfo> criteriaQuery = builder.createQuery(this.entityClass);

        Root<CourseInfo> root = criteriaQuery.from(this.entityClass);
        Path<String> namePath = root.get("couName");
        criteriaQuery.where(builder.equal(namePath, couName));

        TypedQuery<CourseInfo> typedQuery = this.getEntityManager().createQuery(criteriaQuery);

        try{
            return typedQuery.getSingleResult();
        } catch (Exception ex){
            return null;
        }
    }
}
